/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.util;

import javax.xml.namespace.QName;

import org.apache.xmlbeans.XmlCursor;

/** This class helps to determine if a QName is present within the XML.
    This uses the XmlCursor interface to help with this operation. Note that
    if indeed there is such an element, the cursor is appropriately positioned
    at the right location. One can then use xmlText() to retrive the XML text
    and parse accordingly to access sub-elements if any within the element.

    @author Shrideep Pallickara
    $Date: 2005/07/29 22:41:29 $
    $Revision: 1.9 $
*/


public class QNameLocator {
  private static final QNameLocator instance = new QNameLocator();
  private boolean debug = false;
  
  private int tracker=0;
  public String moduleName = "QNameLocator: ";
  
  
  private QNameLocator() {}
  
  
  /* Get the QNameLocator instance */
  public static QNameLocator getInstance() {
    return instance;
  }

  
  /**
     Locate the QName based on the specified XmlCursor. 
     @return true If we are able to successfully locate the QName. Please note
     that the cursor is positioned at the location where the element is 
     successfully located. Note that since the cursor is positioned at the 
     location at which the element is found, this method does not reposition 
     the cursor's temporarily saved location <i>iff</i> it returns a true. 
     Please make sure you use <i>cursor.pop() </i> to erase the stack storage 
     of the temporary location if your program's logic so demands.
     
     <br> Thus, if you did cursor.push() prior to calling this method, and if
     a QName has been located by this method. cursor.pop() at a subsequent time
     can lead to aberrant results. You need to do cursor.pop() again in such
     a scenario.
  */
  public boolean locateQName(XmlCursor cursor, QName qname) {
    tracker++;
    if (!cursor.hasNextToken()) {
      return false;
    }

    if (debug) {
      System.out.println(moduleName + "Searching for QName [" + 
			 qname.getLocalPart() + 
			 "] Tracker=(" + tracker + ")\n" +
			 cursor.xmlText() + 
			 "\n cursor.isEnd()=" + cursor.isEnd() +
			 "\n\n\n");
    }

    boolean found = cursor.toChild(qname);
    if (found) {
      return true;
    }

    /** Save the location of the cursor, since at the end of the recursion 
	the cursor may be positioned somewhere else, and the location scheme 
	will break */
    cursor.push();
       
    int index = 0;
    while (cursor.toChild(index)) {
      found = locateQName(cursor, qname);
      
      if (found) {
	return true;
      }
      index++;
      
      boolean movedToBookmark = cursor.pop();
      if (!movedToBookmark ) {
	System.out.println(moduleName + "Unable to move to created bookmark");
      } else {
	cursor.push(); /** Newly added Dec22*/
      }
    }
    
    /** A pop() has to be called in a scenario where a push() has been 
	previously made, this ensures that the cursor() state is
	not modified in the event that a recursion ends in a failure.*/
    cursor.pop(); /** Newly added Dec22*/
    return false;
  } /* end locateQName() */


  public int locateQNameAndDepth(XmlCursor cursor, QName qname) {
    tracker++;
    if (!cursor.hasNextToken()) {
      return 0;
    }

    if (debug) {
      System.out.println(moduleName + "Searching for QName [" + 
			 qname.getLocalPart() + 
			 "] Tracker=(" + tracker + ")\n" +
			 cursor.xmlText() + 
			 "\n cursor.isEnd()=" + cursor.isEnd() +
			 "\n\n\n");
    }

    /** Save the location of the cursor, since at the end of the recursion 
	the cursor may be positioned somewhere else, and the location scheme 
	will break. This also ensures that if a match is indeed found the
	cursor.pop() will position the cursor at the location of the PARENT*/
    cursor.push();

    boolean found = cursor.toChild(qname);
    if (found) {
      return 1;
    }
    
    int index = 0;
    while (cursor.toChild(index)) {
      int depth = locateQNameAndDepth(cursor, qname);
      
      if (depth != 0) {
	depth++;
	return depth;
      }
      index++;
      
      boolean movedToBookmark = cursor.pop();
      if (!movedToBookmark ) {
	System.out.println(moduleName + "Unable to move to created bookmark");
      } else {
	cursor.push(); /** Newly added Dec22*/
      }
    }
    
    /** A pop() has to be called in a scenario where a push() has been 
	previously made, this ensures that the cursor() state is
	not modified in the event that a recursion ends in a failure.*/
    cursor.pop(); /** Newly added Dec22*/
    return 0;
  } /* end locateQName() */
  
} /* end QNameLocator */

